module.exports = app => {
    const express = require('express')
    var fs = require('fs')
    const money = require('../../models/money')
    var request = require('request')
    var xmlreader = require("xmlreader")
    const crypto = require('crypto')
    const xml2js = require('xml2js')
    const customer = require('../../models/customer')
    var jsonBuilder = new xml2js.Builder()// json->xml
    var xmlParser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true })// xml->json
    var xmlparser = require('express-xml-bodyparser');//引入
    const router = express.Router({
        mergeParams: true
    })
    //把金额转为分
    function getmoney(money) {
        return parseFloat(money) * 100;
    }
    // // // 随机字符串产生函数
    // function randomString(len) {
    //     len = len || 32;
    //     var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    //     var maxPos = chars.length;
    //     var pwd = '';
    //     for (i = 0; i < len; i++) {
    //         pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    //     }
    //     return pwd;
    // }

    router.get('/wall', async (req, ress) => {
        console.log(req.query)
        const { sum, local, name, phone } = req.query
        var des = ''
        datas = await money.find({ 'local': local })
        console.log(datas[0].moneys)
        console.log(name)

        if (sum <= datas[0].moneys) {
            var ifname = await customer.find({ account_id: phone, status: 3 }, (err, names) => {
                console.log(err)
                console.log(names)
            })
            console.log(ifname)
            if (ifname.length == 0) {
                ress.send("输入的手机号与姓名有误")
            } else {
                console.log(ifname)
                console.log(ifname[0].default_address[0])
                console.log(ifname[0].default_address[0].name)
                if (ifname[0].default_address[0].name == name) {
                    var list = {
                        amount: getmoney(sum),
                        check_name: 'NO_CHECK',
                        desc: "订单提现",
                        mch_appid: 'wx3f8607ee708aaccb',
                        mchid: '1521320581',
                        nonce_str: Math.random().toString(36).substr(2, 15),
                        openid: req.query.openid,
                        partner_trade_no: req.query.paySigns,
                        spbill_create_ip: req.connection.remoteAddress.split(":")[3],
                        //sign:getsign()
                    }
                    console.log("list0=")
                    console.log(list)
                    console.log("list1=")
                    console.log(list)
                    list.sign = getsign(list)
                    list = jsonBuilder.buildObject(list)
                    console.log('xml=' + list);
                    request.post({
                        url: 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',
                        method: "POST",
                        headers: {
                            "content-type": "application/json",
                        },
                        key: fs.readFileSync(__dirname + '/config/apiclient_key.pem'),
                        cert: fs.readFileSync(__dirname + '/config/apiclient_cert.pem'),
                        body: list
                    }, async function (err, res, body) {

                        console.log("res=")
                        console.log(res.statusCode)

                        if (!err && res.statusCode === 200) {
                            let data = body
                            // console.log(body)
                            xmlParser.parseString(data, function (err, result) {
                                data = result
                            })
                            console.log(data.xml)
                            data = data.xml
                            console.log(data)
                            if (data.result_code === 'FAIL') {
                                des = data.err_code_des
                                console.log("fail==" + des)
                                ress.send(des)
                            } else if (data.result_code === 'SUCCESS') {

console.log(data.result_code)

                                //进行查询企业付款
                                var list1 = {
                                    nonce_str: Math.random().toString(36).substr(2, 15),
                                    partner_trade_no: req.query.paySigns,
                                    mch_id: data.mchid,
                                    appid: 'wx3f8607ee708aaccb',
                                }
                              
                                console.log("list="+list1)
                                list1.sign = getsign(list1)
                                list1 = jsonBuilder.buildObject(list1)
                                request.post({
                                       url: 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo',
                                        method: "POST",
                                        headers: {
                                            "content-type": "application/json",
                                        },
                                        key: fs.readFileSync(__dirname + '/config/apiclient_key.pem'),
                                        cert: fs.readFileSync(__dirname + '/config/apiclient_cert.pem'),
                                        body: list1
                                    }, async function (err, res, body) {
                                        if (!err && res.statusCode === 200) {
                                            let data1 = body
                                            console.log(body)
                                            xmlParser.parseString(data1, function (err, result) {
                                                data1 = result
                                            })
                                            console.log(data1.xml)
                                            
                                            data1 = data1.xml
                                            console.log(data1)
                                            if (data1.status = "SUCCESS") {
                                
                                                //状态成功执行后
                                                var id = req.query.paySigns
                                                var payment_no = "支付成功" //data.payment_no
                                                var title = '钱包提现'
                                                var cash_fee = sum
                                                var addresses = [{
                                                    articleid: id,
                                                    payment_no: payment_no,
                                                    cash_fee: -cash_fee,
                                                    title: title,
                                                    accomplish_time: new Date()
                                                }]
                                                await money.update({ local: local }, { $inc: { "moneys": -cash_fee } }, { upsert: true })
                                                var datass = await money.update({ local: local }, { $addToSet: { "list": addresses } })
                                                des = 'ok'
                                                ress.send(des)
                                            } else {
                                                ress.send(data1.reason)
                                            }
                                
                                        }
                                
                                    })

                            } else {
                                des = data.err_code_des
                                console.log("fail1==" + des)
                                ress.send(des)
                            }



                        } else {
                            console.log("err=")
                            console.log(err)
                            console.log("err=")
                            console.log(err)
                        }
                    })//request end



                } else {
                    ress.send("信息错误，请重新输入")
                }
            }



        } else {
            ress.send("提现超额，请重新输入")
        }


    })

let sss=function(list1){

}


    //生成xml函数
    let fnCreateXml = function (json) {
        let _xml = '';
        for (let key in json) {

            _xml += '<' + key + '>' + json[key] + '</' + key + '>';


        }
        return _xml;
    }

    //签名
    function getsign(datas) {
        //按key值的ascii排序
        const keys = Object.keys(datas).sort();
        const temp = [];
        console.log(keys)
        keys.forEach(v => {
            if (datas[v] && v !== 'sign') {
                temp.push(`${v}=${datas[v]}`);
            }
        });
        temp.push('key=wSV7IfyOHUPYv1MOt8nHckEVOX7cGOhf');// temp.push('key=');
        const ret = temp.join('&');
        //生成签名
        return crypto.createHash('md5').update(ret, 'utf8').digest('hex').toUpperCase();
    }


    app.use('/api/admin', router)
}